<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="活动名称" prop="activityName">
        <el-input
          v-model="queryParams.activityName"
          placeholder="请输入活动名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker clearable
          v-model="queryParams.startTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="活动状态：" prop="activityStatus">
        <el-input
          v-model="queryParams.activityStatus"
          placeholder="请输入活动状态：0-未开始 1-已开始 2-已结束"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['promotion:activitiess:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['promotion:activitiess:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['promotion:activitiess:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['promotion:activitiess:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="activitiessList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="活动名称" align="center" prop="activityName" />
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请截止时间" align="center" prop="applyEndTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.applyEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动状态" align="center" prop="activityStatus">
        <template #default="scope">
          <span>{{ getActivityStatusText(scope.row.activityStatus) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请规则" align="center" prop="applyRule" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- 未开始状态(0)：编辑、管理、关闭 -->
          <template v-if="scope.row.activityStatus === 0">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['promotion:activitiess:edit']">编辑</el-button>
            <el-button link type="success" icon="Setting" @click="handleManage(scope.row)" v-hasPermi="['promotion:activitiess:manage']">管理</el-button>
            <el-button link type="danger" icon="Close" @click="handleClose(scope.row)" v-hasPermi="['promotion:activitiess:close']">关闭</el-button>
          </template>
          <!-- 已开始状态(1)：查看、关闭 -->
          <template v-else-if="scope.row.activityStatus === 1">
            <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['promotion:activitiess:view']">查看</el-button>
            <el-button link type="danger" icon="Close" @click="handleClose(scope.row)" v-hasPermi="['promotion:activitiess:close']">关闭</el-button>
          </template>
          <!-- 已结束状态(2)：查看 -->
          <template v-else-if="scope.row.activityStatus === 2">
            <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['promotion:activitiess:view']">查看</el-button>
          </template>
          <!-- 已关闭状态(3)：编辑 -->
          <template v-else-if="scope.row.activityStatus === 3">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['promotion:activitiess:edit']">编辑</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改秒杀活动对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="activitiessRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="活动名称" prop="activityName">
          <el-input v-model="form.activityName" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable
            v-model="form.startTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="申请截止时间" prop="applyEndTime">
          <el-date-picker clearable
            v-model="form.applyEndTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择申请截止时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="活动状态：0-未开始 1-已开始 2-已结束" prop="activityStatus">
          <el-input v-model="form.activityStatus" placeholder="请输入活动状态：0-未开始 1-已开始 2-已结束" />
        </el-form-item>
        <el-form-item label="申请规则" prop="applyRule">
          <el-input v-model="form.applyRule" placeholder="请输入申请规则" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Activitiess">
import {
  listActivitiess,
  getActivitiess,
  delActivitiess,
  addActivitiess,
  updateActivitiess,
  addTimeSegment
} from "@/api/promotion/activitiess"
import { useRouter } from 'vue-router'

const { proxy } = getCurrentInstance()
const router = useRouter()

const activitiessList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    activityName: null,
    startTime: null,
    activityStatus: null,
  },
  rules: {
    activityName: [
      { required: true, message: "活动名称不能为空", trigger: "blur" }
    ],
    startTime: [
      { required: true, message: "开始时间不能为空", trigger: "blur" }
    ],
    applyEndTime: [
      { required: true, message: "申请截止时间不能为空", trigger: "blur" }
    ],
    activityStatus: [
      { required: true, message: "活动状态：0-未开始 1-已开始 2-已结束不能为空", trigger: "blur" }
    ],
    applyRule: [
      { required: true, message: "申请规则不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询秒杀活动列表 */
function getList() {
  loading.value = true
  listActivitiess(queryParams.value).then(response => {
    activitiessList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    activityName: null,
    startTime: null,
    applyEndTime: null,
    activityStatus: null,
    applyRule: null
  }
  proxy.resetForm("activitiessRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加秒杀活动"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  const _id = row.id || ids.value[0]
  // 跳转到编辑页面
  proxy.$router.push({
    path: '/promotion/activitiess/update',
    query: { id: _id }
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["activitiessRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateActivitiess(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addActivitiess(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除秒杀活动编号为"' + _ids + '"的数据项？').then(function() {
    return delActivitiess(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('promotion/activitiess/export', {
    ...queryParams.value
  }, `activitiess_${new Date().getTime()}.xlsx`)
}

/** 管理按钮操作 */
function handleManage(row) {
  // 跳转到活动管理页面，传递活动ID
  router.push({
    path: '/promotion/activitiess/management',
    query: { id: row.id }
  })
}

/** 查看按钮操作 */
function handleView(row) {
  // 跳转到活动管理页面，传递活动ID和查看模式
  router.push({
    path: '/promotion/activitiess/management',
    query: { id: row.id, mode: 'view' }
  })
}

/** 关闭按钮操作 */
function handleClose(row) {
  proxy.$modal.confirm(`是否确认关闭活动"${row.activityName}"？`).then(function() {
    // 将活动状态设置为3（已关闭）
    const updateData = {
      ...row,
      activityStatus: 3
    }
    return updateActivitiess(updateData)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("活动已关闭")
  }).catch(() => {})
}

/** 获取活动状态文字 */
function getActivityStatusText(status) {
  const statusMap = {
    0: '未开始',
    1: '已开始', 
    2: '已结束',
    3: '已关闭'
  }
  return statusMap[status] || '未知状态'
}

getList()
</script>
